import axios from 'axios'
import useLoginStore from '@/stores/login';
import { ElMessage } from 'element-plus';
import router from '@/router';

const instance = axios.create({
    baseURL: 'http://localhost:4000/api',
    // baseURL: 'http://localhost:8080/zut',
    timeout: 5000
})

const RESPONSE_CODE = {
    success: 10000,
    // success: 1,
    unauthorized: 401
}

instance.interceptors.request.use(function (config) {
    if (config) {
        const loginStore = useLoginStore()
        const { token } = loginStore
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
    const { code, data, message } = response.data
    if (code === RESPONSE_CODE.success)
        return data
    return Promise.reject(new Error(message))
}, function (error) {
    const { status, data: { message } } = error.response
    if (status === RESPONSE_CODE.unauthorized) {
        ElMessage.error(message)
        const loginStore = useLoginStore()
        loginStore.logoutAction()
        const { path: currentPath } = router.currentRoute.value
        router.push(`/login?redirectUrl=${currentPath}`)
    }
    return Promise.reject(error);
});

export default instance